<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use app\admin\model\Admin;
use app\common\model\Materials;

use app\common\model\MaterialWechat;
use think\Db;
/**
 * 微信素材
 *
 * @icon   fa fa-list
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Material extends Backend
{
	protected $noNeedLogin = [''];
    protected $noNeedRight = [''];

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->model = model('app\common\model\MaterialWechat');
    }
    public function index(){
    	if ($this->request->isAjax()) {
    		$map=[];
    		$map['a.wechat_id'] = $this->wechat_id;
            $map['m.is_news'] = 1;
    		list($where, $sort, $order, $offset, $limit) = $this->buildparams("a.title");
    		$list = $this->model->alias("a")
                ->join("materials m","m.id = a.news_id")
                ->field("m.*")
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
			$result = array("total" => $list->total(), "rows" => $list->items());
			return json($result);
    	}
    	return $this->view->fetch();
    }
    public function item(){
        return $this->view->fetch();
    }
    public function add(){
        if($this->request->isPost()){
            $data = $this->request->post('row/a');
            $rows = [];
            $i=0;
            $material_id = 0;
            $mates = $articles = [];
            $wechatIds = [];
            $newsIds = [];
            Db::startTrans();
            try{
                foreach ($data as $key => $items) {
                    foreach($items as $vo){
                        if($vo['name'] == 'title' && empty($vo['value'])){
                            $this->error("请输入标题",'',['index'=>$key]);
                        }
                        if($vo['name'] == 'thumb' && empty($vo['value'])){
                            $this->error("请上传封面",'',['index'=>$key]);
                        }
                        $rows[$i][$vo['name']] = $vo['value'];
                        if($vo['name'] == 'wechatIds' && $vo['value'] > 0 && !in_array($vo['value'],$wechatIds)){
                            $wechatIds[] = $vo['value'];
                        }
                    }
                    unset($rows[$i]['wechatIds'] );
                    $rows[$i]['need_open_comment'] = isset($rows[$i]['need_open_comment']) ? $rows[$i]['need_open_comment'] : 0;
                    $rows[$i]['only_fans_can_comment'] = isset($rows[$i]['only_fans_can_comment']) ? $rows[$i]['only_fans_can_comment'] : 0;
                    $rows[$i]['wechat_id'] = $this->wechat_id;
                    $rows[$i]['created_at'] = time();
                    if($i == 0){
                        $rows[$i]['is_news'] = 1;
                    }
                    $id = db('materials')->insert($rows[$i],true,true);
                    if($i == 0){
                        $material_id = $id;
                    }else{
                        $mates[] = ['material_id'=>$material_id,'news_id'=>$id,'sort'=>$key];
                    }
                    $newsIds[] = $id;
                    $wechat[] = ['wechat_id'=>$this->wechat_id,'news_id'=>$id];

                    $articles[] = array(
                        'title' => $rows[$i]['title'],
                        'author' => $rows[$i]['author'],
                        'thumb_media_id' => $rows[$i]['thumb_media_id'],
                        'show_cover_pic' => 1,
                        'digest' => $rows[$i]['digest'],
                        'content' => $rows[$i]['content'],
                        'content_source_url' => $rows[$i]['content_source_url'],
                        'need_open_comment' => (int)$rows[$i]['need_open_comment'],
                        'only_fans_can_comment' => (int)$rows[$i]['only_fans_can_comment'],
                    );
                    $i++;
                }
                // 同步公众号
                
                if(is_array($wechatIds) && !empty($wechatIds)){
                    foreach($wechatIds as $wechatid){
                        foreach ($newsIds as $key => $news_id) {
                           $this->model->insert(['wechat_id'=>$wechatid,'news_id' => $news_id],true,true);
                        }
                    }
                }
                $result = db('material_mate')->insertAll($mates,true,true);
                $this->model->insertAll($wechat,true,true);
                //$results = $this->updateMaterial($articles);
                // if(!$results || (isset($results['code']) && $results['code'] == -1)){
                //     Db::rollback();
                //     $this->error(isset($results['msg']) ? $results['msg'] : '添加失败...');
                // }   
            }catch (\Exception $e){
                Db::rollback();
                $this->error("保存失败".$e->getMessage());
            }
            Db::commit();
            // $this->model->where('id',$material_id)->update(['media_id' => $results['media_id'],'updated_at'=>time()]);
            $this->success("保存成功",url('index'));
        }
        return $this->view->fetch();
    }
    public function edit($ids=null){
        $row = Materials::get($ids);
        if(empty($row)){
            $this->error('数据不存在');
        }
        if($this->request->isPost()){
            $data = $this->request->post('row/a');
            $rows = [];
            $i=0;
            $material_id = 0;
            $mates = $articles = [];
            Db::startTrans();
            $wechatIds = [];
            $newsIds = [];
            try{
                foreach ($data as $key => $items) {
                    if(!is_array($items)){
                        continue;
                    }
                    foreach($items as $vo){
                        if($vo['name'] == 'title' && empty($vo['value'])){
                            $this->error("请输入标题",'',['index'=>$key]);
                        }
                        if($vo['name'] == 'thumb' && empty($vo['value'])){
                            $this->error("请上传封面",'',['index'=>$key]);
                        }
                        $rows[$i][$vo['name']] = $vo['value'];
                        if($vo['name'] == 'wechatIds' && $vo['value'] > 0 && !in_array($vo['value'],$wechatIds)){
                            $wechatIds[] = $vo['value'];
                        }
                    }
                    unset($rows[$i]['wechatIds'] );
                    $rows[$i]['need_open_comment'] = isset($rows[$i]['need_open_comment']) ? $rows[$i]['need_open_comment'] : 0;
                    $rows[$i]['only_fans_can_comment'] = isset($rows[$i]['only_fans_can_comment']) ? $rows[$i]['only_fans_can_comment'] : 0;
                    $rows[$i]['wechat_id'] = $this->wechat_id;
                    $rows[$i]['updated_at'] = time();
                    if($i == 0){
                        $rows[$i]['is_news'] = 1;
                    }
                    if(intval($rows[$i]['id']) > 0){
                        db('materials')->where('id',$rows[$i]['id'])->update($rows[$i]);
                        $id = $rows[$i]['id'];
                    }else{
                        $id = db('materials')->insert($rows[$i],true,true);
                    }
                    $this->model->insert(['wechat_id'=>$this->wechat_id,'news_id' => $id],true,true);
                    $newsIds[] = $id;
                    if($i == 0){
                        $material_id = $id;
                    }else{
                        $mates[] = ['material_id'=>$material_id,'news_id'=>$id,'sort'=>$key];
                    }
                    $articles[] = array(
                        'title' => $rows[$i]['title'],
                        'author' => $rows[$i]['author'],
                        'thumb_media_id' => $rows[$i]['thumb_media_id'],
                        'show_cover_pic' => 1,
                        'digest' => $rows[$i]['digest'],
                        'content' => $rows[$i]['content'],
                        'content_source_url' => $rows[$i]['content_source_url'],
                        'need_open_comment' => (int)$rows[$i]['need_open_comment'],
                        'only_fans_can_comment' => (int)$rows[$i]['only_fans_can_comment'],
                    );
                    $i++;
                }
                // 同步公众号

                if(is_array($wechatIds)){
                    foreach($wechatIds as $wechatid){
                        foreach ($newsIds as $key => $news_id) {
                           $this->model->insert(['wechat_id'=>$wechatid,'news_id' => $news_id],true,true);
                        }
                    }
                }
                db('material_mate')->where(['material_id'=>$row->id])->delete();
                $result = db('material_mate')->insertAll($mates,true,true);
                // $results = $this->updateMaterial($articles,$row['media_id']);
                // if(!$results || (isset($results['code']) && $results['code'] == -1)){
                //     Db::rollback();
                //     $this->error(isset($results['msg']) ? $results['msg'] : '添加失败...');
                // }

            }catch (\Exception $e){
                Db::rollback();
                $this->error("保存失败".$e->getMessage());
            }
            Db::commit();
            // $this->model->where('id',$material_id)->update(['media_id' => $results['media_id'],'updated_at'=>time()]);
            $this->success("保存成功",url('index'));
        }
        $data = $row->toArray();
        $items = (new Materials)->getMaterialItems($row->id);
        $bases = array_merge(array($data),$items);
        $a = [];
        foreach($bases as $ik=>$fields){
            foreach($fields as $field=>$value){
                $a[$ik][] = ['name'=>$field,'value'=>$value];
            }
        }
        $this->assign('row',$row);
        $this->assign('items',$items);
        $this->assign('oldData',json_encode($a,JSON_UNESCAPED_UNICODE));
        return $this->view->fetch();
    }
    
    // 上传图文消息到微信
    public function updateMaterial($articles=[],$media_id=null){
        // $articles[] = array(
        //     'title' => 'Test...',
        //     'author' => '',
        //     'thumb_media_id' => 'RZWjzggbGaHH88vpXWX0sSeLPC8bxPuhL5_Cpb8CuoU',
        //     'show_cover_pic' => 1,
        //     'digest' => '',
        //     'content' => 'Test...',
        //     'content_source_url' => '',
        //     'need_open_comment' => 0,
        //     'only_fans_can_comment' => 0,
        // );
        // 上传素材到微信
        $options =(new \app\common\model\Wechats)->getById($this->wechat_id);
        $Token_Access = (new \app\common\model\Wechats)->Token_Access($options);
        $weobj = WX($options,$Token_Access);
        // 删除
        if(!empty($media_id)){
            $weobj->deleteMaterials(['media_id'=>$media_id]);
        }
        return $result = $weobj->createMaterials(['articles'=>$articles]);
    }

    public function del($ids = null){
        if(intval($ids) > 0){
            $result = db('materials')->where('id',$ids)->delete();
            if($result){
                db('material_wechat')->where('news_id',$ids)->delete();
                db('material_mate')->where('news_id',$ids)->delete();
                $this->success('删除成功');
            }
        }
        $this->success('删除失败');
    }
}